const utlis = require("./utils")
const { writeFileSync } = require("fs")

let pageNums = 2
let domain = "https://pic.netbian.com"
let BaseUrl = 'https://pic.netbian.com/4kmeinv/'
let PageUrlArr = [];
let PageUrlIndex = 0;

let CurrentPageAllHref = []
let CurrentPageIndex = 0

for (let index = 1; index <= pageNums; index++) {
    PageUrlArr.push( index == 1 ? BaseUrl : `${BaseUrl}index_${index}.html` )
};

getPageHref(PageUrlArr[PageUrlIndex])

async function getPageHref(url) {
    let $ = await utlis.get(url)
    $(".slist ul li a").each(function(i, v) {
        CurrentPageAllHref.push(`${domain}${$(this).attr("href")}`)
    });

    getUrlInfo(CurrentPageAllHref[CurrentPageIndex])
}

async function getUrlInfo(url) {
    let $ = await utlis.get(url)
    let bigImgUrl = $("#img img").attr("src")
    let fileName = bigImgUrl.substr(bigImgUrl.lastIndexOf("/")+1)
    downImg(fileName,`${domain}${bigImgUrl}`)
}

async function downImg(fileName,url) {
    let imgBuffer = await utlis.get(url,"img");
    writeFileSync(`./img/${fileName}`,imgBuffer)
    CurrentPageIndex+=1
    if (CurrentPageIndex < CurrentPageAllHref.length) {
        getUrlInfo(CurrentPageAllHref[CurrentPageIndex])
    } else {
        CurrentPageIndex = 0;
        CurrentPageAllHref= []
        PageUrlIndex += 1 
        if (PageUrlIndex < PageUrlArr.length) {
            getPageHref(PageUrlArr[PageUrlIndex])
        }
    }
}
